package com.ehotting.edsta.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.ehotting.eaf.core.constant.HttpStatus;
import com.ehotting.eaf.core.constant.SecurityConstants;
import com.ehotting.eaf.core.domain.system.api.SysDictData;
import com.ehotting.eaf.core.exception.ServiceException;
import com.ehotting.eaf.core.utils.StringUtils;
import com.ehotting.eaf.core.web.domain.AjaxResult;
import com.ehotting.edsta.auth.config.SmsConfig;
import com.ehotting.edsta.auth.service.impl.SysLoginService;
import com.ehotting.edsta.auth.utils.StringHelper;
import com.ehotting.eaf.core.constant.UserConstants;
import com.ehotting.eaf.core.domain.R;
import com.ehotting.eaf.core.enums.UserTypeEnum;
import com.ehotting.eaf.core.utils.SecurityUtils;
import com.ehotting.eaf.core.web.controller.BaseController;
import com.ehotting.eaf.redis.service.RedisService;
import com.ehotting.eaf.core.domain.system.api.SysUser;
import com.ehotting.edsta.system.api.RemoteUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息
 * 
 * @author edsta
 */
@RestController
@RequestMapping("/user")
@Api(tags = "UserController", description = "c端用户相关接口")
public class UserController extends BaseController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 注册用户信息
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public R<Boolean> register(@RequestBody SysUser sysUser) {

        if (StringUtils.isEmpty(sysUser.getMcCpu()) || StringUtils.isEmpty(sysUser.getMcMac())
                ||StringUtils.isEmpty(sysUser.getMcBoard())) {
            return R.fail("提交的机器码为空，请检查软件版本");
        }

        String phonenumber = sysUser.getPhonenumber();
        String userSmsCode = sysUser.getUserSmsCode();
        checkSmsCode(phonenumber, userSmsCode, SmsConfig.REGISTER_SMS_CODE);

        String username = sysUser.getUserName();
        if (UserConstants.NOT_UNIQUE.equals(loginService.checkUserNameUnique(username))) {
            throw new ServiceException("注册用户'" + username + "'失败，账号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(loginService.checkPhoneUnique(sysUser))) {
            // 用户名和手机号都要唯一
            throw new ServiceException("注册失败，该手机号'" + phonenumber + "'已存在注册账号");
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        sysUser.setUserType(UserTypeEnum.client.getType());
        String machineCode = sysUser.getMcBoard() + "+" + sysUser.getMcCpu() + "+" + sysUser.getMcMac();
        sysUser.setMachineCode(machineCode);
        redisService.delete(SmsConfig.REGISTER_SMS_CODE + phonenumber);
        return R.ok(loginService.registerUser(sysUser));
    }

    private void checkSmsCode(String phonenumber,String userSmsCode,String redisKey) {
        String redisSmsCode = redisService.get(redisKey + phonenumber);

        if (!StringHelper.hasText(redisSmsCode)){
            throw new ServiceException("短信验证码已过期");
        }

        logger.info("redisSmsCode[{}],userSmsCode[{}]",redisSmsCode, userSmsCode);

        if(!StringHelper.hasText(userSmsCode)){
            throw new ServiceException("短信验证码不可为空");
        }

        if(!redisSmsCode.equals(userSmsCode)){
            throw new ServiceException("验证码不正确");
        }
    }

    /**
     * 注册用户信息
     */
    @PostMapping("/resetPwd")
    @ApiOperation("重置用户密码")
    public AjaxResult resetPwd(@RequestBody SysUser sysUser) {

        String phonenumber = sysUser.getPhonenumber();
        String userSmsCode = sysUser.getUserSmsCode();
        checkSmsCode(phonenumber, userSmsCode,SmsConfig.RESET_PWD_SMS_CODE);

        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        AjaxResult result = remoteUserService.resetPwd4Client(sysUser);

        if (result.get(AjaxResult.CODE_TAG).toString().equals(String.valueOf(HttpStatus.ERROR))){
            result.put(AjaxResult.MSG_TAG,"该手机号非注册手机号");
            return result;
        }

        return result;
    }

}
